<script lang="ts">
    import { onMount } from 'svelte';
    // import { get, post } from '../../utils/api';
    // import { addToast } from '../../stores/toastStore';
    import Header from '../../../components/common/Header.svelte';

    let content = '';
    let controller;

    onMount(() => {
    });

    const fetchStream = async () => {
        controller = new AbortController();
        const signal = controller.signal;

        try {
            // let url = 'http://localhost:8080/response/stream'; // golang test
            // let url = 'http://localhost:7000/api/task/task/stream'; // goframe task
            let url = 'http://localhost:9503/api/v1/text/chat/stream'; // media media

            const response = await fetch(url, { signal });
            const reader = response.body.getReader();
            const decoder = new TextDecoder('utf-8');

            while (true) {
                const { done, value } = await reader.read();
                if (done) {
                    console.log('Stream complete');
                    break;
                }

                const chunk = decoder.decode(value, { stream: true });
                const items = chunk.split('\n').filter(msg => msg.trim() !== '');

                for (let i in items) {
                    console.log("sse: ", items[i]);
                    if ( items[i]!='[DONE]' ) {
                        const data = JSON.parse(items[i]);
                        content += data.choices[0].delta.content;
                    }
                }
            }
        } catch (error) {
            if (error.name === 'AbortError') {
                console.log('Stream request was aborted');
            } else {
                console.error('Error occurred while connecting to Stream:', error);
            }
        }
    };
    const stopStream = () => {
        if (controller) {
            controller.abort();
            console.log('Stream request manually stopped');
        }
    };
    function startRequest() {
        fetchStream();
    }
    function stopRequest() {
        stopStream();
    }
</script>

<main>
    <Header />
    <div class="flex px-8 py-4 space-x-8">
        <div class="flex-1 bg-white rounded shadow p-4">
            <div class="flex space-x-4 mb-4">
                <button class="bg-gray-200 rounded-full px-4 py-2" on:click={startRequest}>开始</button>
                <button class="bg-gray-200 rounded-full px-4 py-2" on:click={stopRequest}>结束</button>
            </div>
            <textarea class="w-full h-64 border rounded p-2" placeholder="请输入文本...">{content}</textarea>
            <div class="text-right text-gray-500 mt-2">0/1000</div>
        </div>     
    </div>
</main>
